package leetcode; /**
 * description:
 * author:zt
 * date:2021-08-29
 */

/**
 * 给你一个正整数 n ，生成一个包含 1 到 n2 所有元素，且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
 */
public class leetcode59 {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int top=0, left=0, right=n-1, bottom=n-1;
        int index = 1;
        while (true){
            for (int i = left; i <= right; i++) res[top][i] = index++;
            if (++top>bottom) break;
            for (int i = top; i <= bottom; i++) res[i][right] = index++;
            if (--right<left) break;
            for (int i = right; i >= left; i--) res[bottom][i] = index++;
            if (--bottom<top) break;
            for (int i = bottom; i >= top; i--) res[i][left] = index++;
            if (++left>right) break;
        }
        return res;
    }
}
